package com.merlin.demo_wellshape.service;

import com.merlin.demo_wellshape.dto.DailyPlanDTO;
import com.merlin.demo_wellshape.dto.ExercisePlanDTO;
import com.merlin.demo_wellshape.pojo.DailyPlan;
import com.merlin.demo_wellshape.pojo.ExercisePlan;
import com.merlin.demo_wellshape.pojo.User;
import com.merlin.demo_wellshape.repository.DailyPlanRepository;
import com.merlin.demo_wellshape.repository.ExercisePlanRepository;
import com.merlin.demo_wellshape.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DailyPlanService implements DailyPlanServiceImpl {

    @Autowired
    private DailyPlanRepository dailyPlanRepository;

    @Autowired
    private ExercisePlanRepository exercisePlanRepository;

    @Autowired
    private UserRepository userRepository;

    // 获取所有计划
    public List<DailyPlanDTO> getAllPlansByUserId(int userId) {
        // 获取所有计划
        List<DailyPlan> dailyPlans = dailyPlanRepository.findByUser_UserId(userId);

        // 按 planDate 分组
        Map<LocalDate, List<DailyPlan>> groupedByDate = dailyPlans.stream()
                .collect(Collectors.groupingBy(DailyPlan::getPlanDate));

        // 创建 DailyPlanDTO 列表
        List<DailyPlanDTO> dailyPlanDTOs = new ArrayList<>();
        int dailyPlanIdCounter = 1; // 自增的 dailyPlanId 计数器

        for (Map.Entry<LocalDate, List<DailyPlan>> entry : groupedByDate.entrySet()) {
            LocalDate planDate = entry.getKey();
            List<DailyPlan> plans = entry.getValue();

            // 创建一个新的 DailyPlanDTO
            DailyPlanDTO dailyPlanDTO = new DailyPlanDTO();
            dailyPlanDTO.setDailyPlanId(dailyPlanIdCounter++); // 设置自增的 dailyPlanId
            dailyPlanDTO.setPlanDate(planDate);

            // 合并所有 ExercisePlan
            List<ExercisePlanDTO> exercisePlanDTOs = plans.stream()
                    .flatMap(dp -> dp.getPlans().stream())
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());

            dailyPlanDTO.setPlans(exercisePlanDTOs);
            dailyPlanDTOs.add(dailyPlanDTO);
        }

        // 按 planDate 递增排序（最新日期在下面）
        dailyPlanDTOs.sort(Comparator.comparing(DailyPlanDTO::getPlanDate));

        return dailyPlanDTOs;
    }

    // 添加计划
    @Override
    public DailyPlan addPlan(int userId, LocalDate planDate, String planName, String quantity, boolean completed) {
        // 检查是否存在相同的计划
        // if (exercisePlanRepository.existsByDailyPlan_User_UserIdAndDailyPlan_PlanDateAndPlanNameAndQuantity(userId, planDate, planName, quantity)) {
        //     throw new IllegalArgumentException("该计划已经存在");
        // }

        // 获取用户
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));

        // 创建新的 DailyPlan
        DailyPlan dailyPlan = new DailyPlan();
        dailyPlan.setPlanDate(planDate);
        dailyPlan.setUser(user);

        // 创建新的 ExercisePlan
        ExercisePlan exercisePlan = new ExercisePlan();
        exercisePlan.setPlanName(planName);
        exercisePlan.setQuantity(quantity);
        exercisePlan.setCompleted(completed);
        exercisePlan.setDailyPlan(dailyPlan);

        // 设置 DailyPlan 的 plans 列表
        dailyPlan.setPlans(List.of(exercisePlan));

        // 保存 DailyPlan 到数据库
        return dailyPlanRepository.save(dailyPlan);
    }

    // 更新计划
    @Override
    public ExercisePlanDTO updatePlan(int planId, String planName, String quantity, boolean completed) {
        // 查找 ExercisePlan
        ExercisePlan exercisePlan = exercisePlanRepository.findById(planId)
                .orElseThrow(() -> new IllegalArgumentException("计划不存在"));

        // 更新 ExercisePlan 字段
        exercisePlan.setPlanName(planName);
        exercisePlan.setQuantity(quantity);
        exercisePlan.setCompleted(completed);

        // 保存更新后的 ExercisePlan 到数据库
        ExercisePlan updatedPlan = exercisePlanRepository.save(exercisePlan);

        // 返回 ExercisePlanDTO
        return convertToDTO(updatedPlan);
    }

    // 删除计划
    @Override
    public void deletePlan(int planId) {
        // 查找 ExercisePlan
        ExercisePlan exercisePlan = exercisePlanRepository.findById(planId)
                .orElseThrow(() -> new IllegalArgumentException("计划不存在"));

        // 获取 ExercisePlan 所属的 DailyPlan
        DailyPlan dailyPlan = exercisePlan.getDailyPlan();

        // 删除 ExercisePlan
        exercisePlanRepository.delete(exercisePlan);

        // 检查 DailyPlan 是否还有其他计划
        if (dailyPlan.getPlans().isEmpty()) {
            // 如果没有其他计划，则删除 DailyPlan
            dailyPlanRepository.delete(dailyPlan);
        }
    }

    // 将 DailyPlan 转换为 DTO
    @Override
    public DailyPlanDTO convertToDTO(DailyPlan dailyPlan) {
        DailyPlanDTO dailyPlanDTO = new DailyPlanDTO();
        dailyPlanDTO.setDailyPlanId(dailyPlan.getDailyPlanId());
        dailyPlanDTO.setPlanDate(dailyPlan.getPlanDate());
        dailyPlanDTO.setPlans(dailyPlan.getPlans().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList()));
        return dailyPlanDTO;
    }

    // 将 ExercisePlan 转换为 DTO
    @Override
    public ExercisePlanDTO convertToDTO(ExercisePlan exercisePlan) {
        ExercisePlanDTO exercisePlanDTO = new ExercisePlanDTO();
        exercisePlanDTO.setPlanId(exercisePlan.getPlanId());
        exercisePlanDTO.setPlanName(exercisePlan.getPlanName());
        exercisePlanDTO.setQuantity(exercisePlan.getQuantity());
        exercisePlanDTO.setCompleted(exercisePlan.isCompleted());
        return exercisePlanDTO;
    }

}
